package com.rent.common.storage;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.rent.common.service.StorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Service
@ConditionalOnProperty(name = "rent.upload.type", havingValue = "ali")
public class AliyunOssStorageService implements StorageService {

    @Value("${rent.upload.ali.endpoint}")
    private String endpoint;

    @Value("${rent.upload.ali.access-key-id}")
    private String accessKeyId;

    @Value("${rent.upload.ali.access-key-secret}")
    private String accessKeySecret;

    @Value("${rent.upload.ali.bucket-name}")
    private String bucketName;

    @Value("${rent.upload.ali.domain}")
    private String domain;

    private OSS ossClient;

    @PostConstruct
    public void init() {
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    @Override
    public String upload(String prefix, MultipartFile file) throws IOException {
        // 生成文件路径和名称
        String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        String originalFilename = file.getOriginalFilename();
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String key = prefix + "/" + datePath + "/" + UUID.randomUUID() + extension;

        // 创建临时文件
        File tempFile = Files.createTempFile("upload_", extension).toFile();
        file.transferTo(tempFile);

        try {
            // 上传到阿里云OSS
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, tempFile);
            ossClient.putObject(putObjectRequest);

            // 删除临时文件
            tempFile.delete();

            // 返回可访问的URL
            if (domain != null && !domain.isEmpty()) {
                return domain + "/" + key;
            } else {
                return "https://" + bucketName + "." + endpoint + "/" + key;
            }
        } catch (Exception e) {
            // 删除临时文件
            tempFile.delete();
            throw new IOException("上传文件到阿里云OSS失败", e);
        }
    }

    @Override
    public void delete(String filePath) throws IOException {
        try {
            String key;
            if (domain != null && !domain.isEmpty() && filePath.startsWith(domain)) {
                key = filePath.substring(domain.length() + 1);
            } else {
                // 从默认URL中提取key
                String prefix = "https://" + bucketName + "." + endpoint + "/";
                key = filePath.substring(prefix.length());
            }

            // 删除OSS中的对象
            ossClient.deleteObject(bucketName, key);
        } catch (Exception e) {
            throw new IOException("从阿里云OSS删除文件失败", e);
        }
    }
}
